package pl.edu.agh.inpema.core.components;

import java.util.Iterator;
import java.util.Set;

import javax.jms.JMSException;

import pl.edu.agh.inpema.core.dataBase.DataBase;
import pl.edu.agh.inpema.core.model.Profile;
import pl.edu.agh.inpema.core.model.Receiver;
import pl.edu.agh.inpema.core.queue.Queue;
import pl.edu.agh.inpema.core.queue.QueueMessage;

public class ReadOnlyReceiver extends Thread implements Receiver {

	private ReceiverUtil receiverUtil;
	private boolean isRunning = false;
	
	private Integer environmentId;
	private Set<String> fieldTypes;
	
	private DataBase dataBase;
	private Queue queue;
	
	private boolean isError = false;
	
	public String[] getMessageFieldTypes() {
		return null;
	}

	public ReceiverUtil getReceiverUtil() {
		return this.receiverUtil;
	}

	public boolean isGatheringRunning() {
		return this.isRunning;
	}

	public void setReceiverUtil(ReceiverUtil util) {
		this.receiverUtil = util;
	}

	public void startGathering() {
		this.isRunning = true;
		this.start();
	}

	public boolean stopGathering() {
		this.isRunning = false;
		return this.isError;
	}
	
	public void run() {
		this.isError = false;
		Set<String> analyzersListeners = this.receiverUtil.getAllAnalyzerNames();
		String receiverName = this.receiverUtil.getReceiverName();
		//System.out.println(receiverName);
		if (analyzersListeners != null) {
			Set<Profile> profiles = this.dataBase.getAllProfilesForReceiver(receiverName, this.environmentId);
			Iterator<Profile> profileIterator = profiles.iterator();
			while (profileIterator.hasNext() && this.isRunning) {
				Profile profile = profileIterator.next();
				Set<Integer> messagesId = this.dataBase.getAllMessagesIdForProfile(profile.getProfileId());
				//System.out.println(profile.getProfileId() + ": " + messagesId);
				try {
					Iterator<Integer> messagesIterator = messagesId.iterator();
					while (messagesIterator.hasNext() && this.isRunning) {
						Integer messageId = messagesIterator.next();
						QueueMessage queueMessage = new QueueMessage(receiverName, messageId);
						for (String analyzerName : analyzersListeners) {
							this.queue.sendMessageToAnalyzer(analyzerName, queueMessage);
						}
						/*try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}*/
					}
				} catch (JMSException e) {
					e.printStackTrace();
					this.isError = true;
				}
			}
		}
		this.isRunning = false;
	}
	
	public void setFieldTypes(Set<String> fieldTypes) {
		this.fieldTypes = fieldTypes;
	}
	
	public void setEnvironmentId(Integer environmentId) {
		this.environmentId = environmentId;
	}
	
	public void setDataBase(DataBase dataBase) {
		this.dataBase = dataBase;
	}
	
	public void setQueue(Queue queue) {
		this.queue = queue;
	}
}
